package com.bckj.fastboot.core.extra.mongo;

import com.bckj.fastboot.core.lang.model.PageResult;
import com.mongodb.client.result.UpdateResult;
import lombok.Getter;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;

import java.util.Collection;
import java.util.List;

/**
 * AbstractMongoRepository
 *
 * @author wfc
 **/
@SuppressWarnings("ALL")
@Getter
public class AbstractMongoRepository<Entity, ID> implements IMongoRepository<Entity, ID> {

    private final MongoOps mongoOps;
    private final Class<Entity> entityClass;
    private final String collectionName;

    public AbstractMongoRepository(MongoOps mongoOps, Class<Entity> entityClass, String collectionName) {
        this.mongoOps = mongoOps;
        this.entityClass = entityClass;
        this.collectionName = collectionName;
    }

    @Override
    public boolean save(Entity entity) {
        mongoOps.insert(entity);
        return true;
    }

    @Override
    public boolean saveBatch(Collection<Entity> entities) {
        mongoOps.insertAll(entities);
        return true;
    }

    @Override
    public boolean updateById(Entity entity) {
        mongoOps.save(entity, collectionName);
        return true;
    }

    @Override
    public boolean updateBatchById(Collection<Entity> entities) {
        entities.forEach(this::updateById);
        return true;
    }

    @Override
    public UpdateResult updateFirst(Query query, Update update) {
        return mongoOps.updateFirst(query, update, collectionName);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update) {
        return mongoOps.updateMulti(query, update, collectionName);
    }

    @Override
    public boolean removeById(ID id) {
        return mongoOps.removeById(id, entityClass, collectionName);
    }

    @Override
    public Entity findById(ID id) {
        return mongoOps.findById(id, entityClass, collectionName);
    }

    @Override
    public <T> T findById(ID id, Class<T> entityClass) {
        return mongoOps.findById(id, entityClass, collectionName);
    }

    @Override
    public List<Entity> find(Query query) {
        return mongoOps.find(query, entityClass, collectionName);
    }

    @Override
    public <T> List<T> find(Query query, Class<T> entityClass) {
        return mongoOps.find(query, entityClass, collectionName);
    }

    @Override
    public PageResult<Entity> page(Pageable pageable, Query query) {
        return mongoOps.page(pageable, query, entityClass, collectionName);
    }

    @Override
    public <T> PageResult<T> page(Pageable pageable, Query query, Class<T> entityClass) {
        return mongoOps.page(pageable, query, entityClass, collectionName);
    }

}
